package org.ahuanlien.crm.service.impl;

import org.ahuanlien.crm.domain.Employee;
import org.ahuanlien.crm.domain.Menu;
import org.ahuanlien.crm.mapper.MenuMapper;
import org.ahuanlien.crm.service.IMenuService;
import org.ahuanlien.crm.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;

@Service
public class MenuServiceImpl implements IMenuService {

	@Autowired
	private MenuMapper menuMapper;


	public List<Menu> selectAll() {
		return menuMapper.selectAll();
	}

	public void saveOrUpdate(Menu record) {
		if (record.getId() != null) {
			menuMapper.updateByPrimaryKey(record);
		} else {
			menuMapper.insert(record);
		}
	}

	public void deleteByPrimaryKey(Long id) {
		menuMapper.deleteByPrimaryKey(id);
	}

	public List<Menu> selectRootMenu() {
		return menuMapper.selectRootMenu();
	}


	public List<Menu> selectMenuByEmployee() {
		//获取到当前用户
		Employee currentUser = UserContext.getCurrentUser();
		//查询到所有菜单
		List<Menu> menus = menuMapper.selectRootMenu();
		//若是超级管理员则直接返回
		if (!currentUser.getAdmin()) {
			//遍历比较该员工拥有的菜单
			List<Long> ids = menuMapper.selectMenuByEmployeeId(currentUser.getId());
			checkMenu(menus, ids);
		}
		return menus;
	}

	private void checkMenu(List<Menu> menus, List<Long> ids) {
		Iterator<Menu> iterator = menus.iterator();
		while (iterator.hasNext()) {
			Menu menu = iterator.next();
			if (!ids.contains(menu.getId())) {
				iterator.remove();
				continue;
			}
			//如果当前菜单还有子菜单则继续递归
			if (menu.getChildren().size() > 0) {
				checkMenu(menu.getChildren(), ids);
			}
		}
	}
}
